package com.sl.au.service.impl;


import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.entity.News;
import com.sl.au.entity.Part;
import com.sl.au.repository.NewsRepository;
import com.sl.au.service.NewsService;

@Service("NewsService")
@Transactional
public class NewsServiceImpl extends BaseServiceImpl implements NewsService{
	
	@Autowired
	NewsRepository newsRepository;

	@Override
	public NewsRepository getRepository() {
		return this.newsRepository;
	}

	@Override
	public void savaNews(News news) {
		News newsObj = null;
		if(news.getId().equals("")) {
			newsObj = new News();
		}else {
			newsObj = newsRepository.findOne(news.getId());
			newsObj.setUpdateTime(new Date());
		}
		newsObj.setNewsContent(news.getNewsContent());
		newsObj.setNewsTitle(news.getNewsTitle());
		newsObj.setUser(news.getUser());
		newsObj.setNewsPicture(news.getNewsPicture());
		newsObj.setNewsDescribe(news.getNewsDescribe());
		newsRepository.save(newsObj);
	}

	@Override
	public List<News> getNewsByKey(int start, int length, String key, String orderName, String dir) {
		Page<News> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if(key != null && org.springframework.util.StringUtils.hasText(key)) {
			pages = newsRepository.getNewsByKey(key, pageable);
		}else {
			pages = newsRepository.findAll(pageable);
		}
		return pages.getContent();
	}

	@Override
	public int getNewsByKeyCount(String key) {
		Page<News> pages = null;
		Pageable pageable = new PageRequest(0, Integer.MAX_VALUE);
		if(key != null && org.springframework.util.StringUtils.hasText(key)) {
			pages = newsRepository.getNewsByKey(key, pageable);
		}else {
			pages = newsRepository.findAll(pageable);
		}
		return pages.getContent().size();
	}

}
